<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片项 -->
    <el-card class="box-card">
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectedCates"
            :options="goodsCategoriesList"
            :props="cascaderProps"
            @change="getCate"
            clearable
          ></el-cascader>
          <!-- tab栏区域 -->
          <el-tabs v-model="tabName" @tab-click="tabClick">
            <!-- 添加静态参数的面板 -->
            <el-tab-pane label="静态参数" name="only">
              <el-button
                type="primary"
                :disabled="isBtnDisabled"
                @click="openAddParamsDialog"
                >添加参数</el-button
              >
              <!-- 静态参数表格 -->
              <el-table :data="onlyTableData" stripe border style="width: 100%">
                <el-table-column type="expand" >
                  <template slot-scope="scope">
                    <div>
                      <el-tag
                        v-for="(item, index) in scope.row.attr_vals"
                        :key="index"
                        closable
                        @close="handleClose(index,scope.row)"
                        >{{ item }}</el-tag
                      >
                      <el-input
                        class="input-new-tag"
                        v-if="scope.row.inputVisible"
                        v-model="scope.row.inputValue"
                        ref="saveTagInput"
                        size="small"
                        @keyup.enter.native="handleInputConfirm(scope.row)"
                        @blur="handleInputConfirm(scope.row)"
                        style="width:150px"
                        placeholder="请输入标签名"
                      >
                      </el-input>
                      <el-button
                        v-else
                        class="button-new-tag"
                        size="small"
                        @click="showInput(scope.row)"
                        >+ New Tag</el-button
                      >
                    </div>
                  </template>
                </el-table-column>
                <el-table-column type="index" label="序号"></el-table-column>
                <el-table-column prop="attr_name" label="参数名称">
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <div>
                      <el-button
                        type="primary"
                        icon="el-icon-edit"
                        @click="openEditParamsDialog(scope.row.attr_id)"
                        >修改</el-button
                      >
                      <el-button
                        type="danger"
                        icon="el-icon-delete"
                        @click="removeParam(scope.row.attr_id)"
                        >删除</el-button
                      >
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <!-- 添加动态属性的面板 -->
            <el-tab-pane label="动态属性" name="many">
              <el-button
                type="primary"
                :disabled="isBtnDisabled"
                @click="openAddParamsDialog"
                >添加属性</el-button
              >
              <!-- 动态参数表格 -->
              <el-table :data="manyTableData" stripe border style="width: 100%">
                <el-table-column type="expand" >
                  <template slot-scope="scope">
                    <div>
                      <el-tag
                        v-for="(item, index) in scope.row.attr_vals"
                        :key="index"
                        closable
                        @close="handleClose(index,scope.row)"
                        >{{ item }}</el-tag
                      >
                      <el-input
                        class="input-new-tag"
                        v-if="scope.row.inputVisible"
                        v-model="scope.row.inputValue"
                        ref="saveTagInput"
                        size="small"
                        @keyup.enter.native="handleInputConfirm(scope.row)"
                        @blur="handleInputConfirm(scope.row)"
                        style="width:150px"
                        placeholder="请输入标签名"
                      >
                      </el-input>
                      <el-button
                        v-else
                        class="button-new-tag"
                        size="small"
                        @click="showInput(scope.row)"
                        >+ New Tag</el-button
                      >
                    </div>
                  </template>
                </el-table-column>
                <el-table-column type="index" label="序号"></el-table-column>
                <el-table-column prop="attr_name" label="参数名称">
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <div>
                      <el-button
                        type="primary"
                        icon="el-icon-edit"
                        @click="openEditParamsDialog(scope.row.attr_id)"
                        >修改</el-button
                      >
                      <el-button
                        type="danger"
                        icon="el-icon-delete"
                        @click="removeParam(scope.row.attr_id)"
                        >删除</el-button
                      >
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-card>

    <!-- 添加静态/动态属性的对话框 -->
    <el-dialog
      :title="'添加' + isActive"
      :visible.sync="isAddParamsDialogOpen"
      width="50%"
      @close="addParamsDialogClose"
    >
      <el-form
        :model="addParamsForm"
        :rules="addParamsFormRule"
        ref="addParamsFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="isActive" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isAddParamsDialogOpen = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改静态/动态属性的对话框 -->
    <el-dialog
      :title="'修改' + isActive"
      :visible.sync="isEditParamsDialogOpen"
      width="50%"
      @close="editParamsDialogClose"
    >
      <el-form
        :model="editParamsForm"
        :rules="editParamsFormRule"
        ref="editParamsFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="isActive" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isEditParamsDialogOpen = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //商品种类列表
      goodsCategoriesList: [],
      //商品种类级联下拉框配置项
      cascaderProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      //获取到的商品种类数组
      selectedCates: [],
      //现在选中的tab栏name
      tabName: "only",
      //动态属性
      manyTableData: [],
      //静态属性
      onlyTableData: [],
      //添加静态/动态属性的对话框显隐标志位
      isAddParamsDialogOpen: false,
      //修改静态/动态属性的对话框显隐标志位
      isEditParamsDialogOpen: false,
      //添加属性表单对象
      addParamsForm: {
        attr_name: "",
      },
      //添加属性表单验证规则
      addParamsFormRule: {
        attr_name: [
          { required: true, message: "请输入属性名", trigger: "blur" },
        ],
      },
      //修改属性表单对象
      editParamsForm: {
        attr_name: "",
        attr_id: "",
      },
      //修改属性表单验证规则
      editParamsFormRule: {
        attr_name: [
          { required: true, message: "请输入属性名", trigger: "blur" },
        ],
      }
    };
  },
  created() {
    //获取商品所有的分类
    this.queryGoodsCategories();
  },
  methods: {
    async queryGoodsCategories() {
      const { data: res } = await this.$http.get("/categories");
      if (res.meta.status != 200)
        return this.$message.error("商品分类列表获取失败");
      this.goodsCategoriesList = res.data;
    },
    //监听商品分类选择完成事件
    async getCate() {
      this.getParamsData();
    },
    //获取参数的列表数据
    async getParamsData() {
      if (this.selectedCates.length != 3) {
        this.goodsCategoriesList = []
        this.manyTableData =[]
        this.onlyTableData = []
        return this.$message.error("请选择一个三级分类");
      }
      //选中的是三级分类,发起请求，获取该分类的参数列表
      const { data: res } = await this.$http(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.tabName,
          },
        }
      );
      if (res.meta.status != 200) return this.$message.error("参数获取失败");

      //将参数标签分割为数组
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        //控制文本框的显示与隐藏
        item.inputVisible = false,
        //文本框输入的值
        item.inputValue = ''
      });

      //判断获取的数据是动态属性，还是静态属性
      if (this.tabName == "many") {
        this.manyTableData = res.data;
        console.log(this.manyTableData);
      } else {
        this.onlyTableData = res.data;
      }
    },
    //当tab栏被点击
    tabClick() {
      this.getParamsData();
    },
    //打开添加静态/动态属性的对话框
    openAddParamsDialog() {
      this.isAddParamsDialogOpen = true;
    },
    //打开修改静态/动态属性的对话框
    async openEditParamsDialog(id) {
      this.isEditParamsDialogOpen = true;
      //获取修改行对应信息
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${id}`
      );
      if (res.meta.status != 200) return this.$message.error("参数查询失败");
      this.editParamsForm.attr_name = res.data.attr_name;
      this.editParamsForm.attr_id = res.data.attr_id;
    },
    //添加属性对话框关闭事件
    addParamsDialogClose() {
      this.$refs.addParamsFormRef.resetFields();
    },
    //修改属性对话框关闭事件
    editParamsDialogClose() {
      this.$refs.editParamsFormRef.resetFields();
    },
    //添加商品动态/静态参数
    async addParams() {
      const validateRes = await this.$refs.addParamsFormRef
        .validate()
        .catch((err) => err);
      if (!validateRes) return this.$message.error("参数不符合验证规则");
      const { data: res } = await this.$http.post(
        `categories/${this.cateId}/attributes`,
        {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.tabName,
        }
      );
      if (res.meta.status != 201) return this.$message.error("参数添加失败");
      this.$message.success("参数添加成功");
      this.isAddParamsDialogOpen = false;
      this.getParamsData();
    },
    //修改商品动态/静态参数
    async editParams() {
      const validateRes = await this.$refs.editParamsFormRef
        .validate()
        .catch((err) => err);
      if (!validateRes) return this.$message.error("参数不符合验证规则");
      //发送请求，修改商品参数
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`,
        {
          attr_name: this.editParamsForm.attr_name,
          attr_sel: this.tabName,
        }
      );
      if (res.meta.status != 200) return this.$message.error("参数修改失败");
      this.$message.success("参数修改成功");
      this.isEditParamsDialogOpen = false;
      this.getParamsData();
    },

    //删除商品动态/静态参数
    async removeParam(attr_id) {
      const confirmRes = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      console.log(confirmRes);
      if (confirmRes != "confirm") return;
      const { data: res } = await this.$http.delete(
        `/categories/${this.cateId}/attributes/${attr_id}`
      );
      if (res.meta.status != 200) return this.$message.error("删除失败");
      this.$message.success("删除成功");
      this.getParamsData();
    },

    //监听新增标签按钮点击事件
    showInput(row){
      row.inputVisible = true
      //$nextTick()作用：当页面上元素被重新渲染之后，才会执行指定回调函数中的代码
      this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
    },

    //新增标签输入框确认事件
    handleInputConfirm(row){
      console.log(row);
      if(row.inputValue.trim().length === 0 ){
        row.inputValue = ''
        row.inputVisible = false
      }
      //用户输入了内容，做后续处理
      row.attr_vals.push(row.inputValue)
      row.inputValue = ''
      row.inputVisible = false
      this.saveAttrValues(row)
    },
    async saveAttrValues(row){
      //发起请求，保存标签
      const {data: res} =await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
        attr_name: row.attr_name,
        attr_sel: this.tabName,
        attr_vals: row.attr_vals.join(' ')
      })
      if(res.meta.status != 200) return this.$message.error('参数修改失败')
      this.$message.success('参数修改成功')
    },
    //删除对应的参数可选性
    handleClose(i,row){
      row.attr_vals.splice(i,1)
      this.saveAttrValues(row)
    }
  },
  computed: {
    //判断选择的是否是三级分类，是的话激活按钮
    isBtnDisabled() {
      return !(this.selectedCates.length == 3);
    },
    //判断选择的是否是三级分类，是的话返回三级分类的id
    cateId() {
      if (this.selectedCates.length == 3) {
        return this.selectedCates[2];
      }
      return null;
    },
    //判断是静态属性还是动态属性
    isActive() {
      if (this.tabName == "only") {
        return "静态参数";
      } else {
        return "动态属性";
      }
    },
  },
};
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}

.el-tag {
  margin: 0 10px;
}
</style>